﻿using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace SharpCmd.Windows.Forms.Progress
{
    internal partial class ProgressForm : Form
    {
        public ProgressForm()
        {
            InitializeComponent();
            Worker = new BackgroundWorker();
            Worker.WorkerReportsProgress = true;
            Worker.WorkerSupportsCancellation = true;
            Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(WorkCompleted);
            Worker.ProgressChanged += new ProgressChangedEventHandler(ProgressChanged);
            Worker.DoWork += new DoWorkEventHandler(DoWork);
        }

        protected void AttachHandlers()
        {
            CancelButton.Click += new EventHandler(CancelButton_Click);
            PauseButton.Click += new EventHandler(PauseButton_Click);
        }

        #region buttons
        private void PauseButton_Click(object sender, EventArgs e)
        {
            if (Paused)
            {
                this.Text = Title + " - SharpCmd";
                PauseButton.Text = "Pause";
            }
            else
            {
                this.Text = string.Format("Paused {0} - SharpCmd", Title);
                PauseButton.Text = "Resume";
            }
            Paused = !Paused;
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            if (Paused)
                Paused = false;
            Worker.CancelAsync();
        }
        #endregion

        protected virtual void DoWork(object sender, DoWorkEventArgs e)
        {
            throw new NotImplementedException();
        }

        protected virtual void ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ProgressInfo progress = e.UserState as ProgressInfo;
            FileNameLabel.Text = progress.CurrentItem;
            ProgressBar.Value = progress.CurrentIndex;
        }

        protected virtual void WorkCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MainForm.Instance.Reload();
            Close();
        }

        protected void HandlePause()
        {
            while (Paused)
                Thread.Sleep(50);
        }

        protected bool Paused;
        protected Button PauseButton;
        protected new Button CancelButton;
        protected Label FileNameLabel;
        protected ProgressBarWithText ProgressBar;
        protected BackgroundWorker Worker { get; set; }
        protected string Title = "ProgressForm";
    }
}
